import { ElMessage } from "element-plus";
import { reactive, ref, watch } from "vue";
import { request } from "../../../utils/request";
import { getCourse, saveCourse } from "../../../api/modules/course";
import { useUserStore } from "../../../store/user";
import { downloadFile } from "../../../api/modules/file";

interface Project {
  file?: File;
  name: string;
}

export const courseList = ref<Course[]>([]); // tod

export function getCourseList(id?: string) {
  request({
    fn: getCourse,
    params: [id],
    async success(res) {
      courseList.value = res.data;
      console.log(courseList.value);
      for (let i = 0, len = courseList.value.length; i < len; i++) {
        const item = courseList.value[i];
        const files = item.files;
        if (!files) continue;
        for (let i = 0, len = files.length; i < len; i++) {
          const item = files[i];
          const res = await downloadFile(item.fileUrl);
          const blob = new Blob([res as any]);
          item.fileUrl = URL.createObjectURL(blob);
        }
      }
    },
  });
}

export interface Course {
  id: number;
  name: string;
  createdTime: string;
  createdByName: string;
  files: { fileUrl: string; type: string }[];
}

export function useProject() {
  const { userInfo } = useUserStore();
  const courseDialogVisible = ref(false);
  const project = reactive<Project>({
    name: "",
  });

  watch(
    () => courseDialogVisible.value,
    (val) => {
      if (val) {
        project.file = undefined;
        project.name = "";
      }
    }
  );

  function handleUploadProject() {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "video/*";
    input.onchange = () => {
      const file = input.files?.[0];
      if (file) {
        if (!/.(mp4|avi|mov|wmv|flv|mpeg|mpg|m4v|webm)$/.test(file.name)) {
          ElMessage.error("请上传视频文件");
          return;
        }
        project.file = file;
        input.remove();
      }
    };
    input.click();
  }

  function saveProject() {
    if (!project.file) {
      ElMessage.error("请上传视频文件");
      return;
    }
    const formData = new FormData();
    formData.append("file", project.file);
    formData.append("name", project.name);
    request({
      fn: saveCourse,
      params: [formData],
      success() {
        ElMessage.success("上传成功");
        courseDialogVisible.value = false;
        getCourseList(userInfo.value.id);
      },
    });
  }

  return {
    project,
    courseList,
    courseDialogVisible,
    handleUploadProject,
    saveProject,
    getCourseList,
  };
}
